package org.example.forum.service.impl;

import lombok.extern.slf4j.Slf4j;
import org.example.forum.common.AppResult;
import org.example.forum.common.ResultCode;
import org.example.forum.dao.UserMapper;
import org.example.forum.exception.ApplicationException;
import org.example.forum.model.Board;
import org.example.forum.model.User;
import org.example.forum.service.IUserService;
import org.example.forum.utils.MD5Util;
import org.example.forum.utils.OSSUtil;
import org.example.forum.utils.StringUtil;
import org.example.forum.utils.UUIDUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.actuate.metrics.cache.CacheMetricsRegistrar;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.Date;
import java.util.UUID;

@Service
@Slf4j
public class UserServiceImpl implements IUserService {
    @Resource
    private UserMapper userMapper;

    @Override
    public void createNormalUser(User user) {
        //1、非空校验
        if(user == null|| StringUtil.isEmpty(user.getUsername())
                || StringUtil.isEmpty(user.getNickname())
                || StringUtil.isEmpty(user.getPassword())
                || StringUtil.isEmpty(user.getSalt())) {
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            //统一抛出ApplicationException
            throw new ApplicationException(AppResult.failure(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        //2、根据用户名查询到用户信息
        User tmpUser = userMapper.selectByUserName(user.getUsername());
        if(tmpUser != null){
            log.info(ResultCode.FAILED_USER_EXISTS.toString());
            throw new ApplicationException(AppResult.failure(ResultCode.FAILED_USER_EXISTS));
        }
        //3、新增用户，设置默认值
        user.setGender((byte)2);
        user.setArticleCount(0);
        user.setIsAdmin((byte)0);
        user.setState((byte)0);
        user.setDeleteState((byte)0);
        Date date =new Date();
        user.setCreateTime(date);
        user.setUpdateTime(date);

        int row = userMapper.insertSelective(user);
        if(row != 1){
            log.warn(ResultCode.FAILED_CREATE.toString());
            throw new ApplicationException(AppResult.failure(ResultCode.FAILED_CREATE));
        }
        log.info("新增用户 user = {}", user.getUsername());
    }

    @Override
    public User selectByUserName(String username) {
        if(StringUtil.isEmpty(username)){
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            throw new ApplicationException(AppResult.failure(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        //返回查询结果
        return userMapper.selectByUserName(username);
    }

    @Override
    public User login(String username, String password) {
        //1、非空校验
        if(StringUtil.isEmpty(username) || StringUtil.isEmpty(password)){
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            throw new ApplicationException(AppResult.failure(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        //2、查询用户信息
        User user = selectByUserName(username);
        //3、用户信息非空校验
        if(user == null){
            log.warn(ResultCode.FAILED_USER_NOT_EXISTS.toString());
            throw new ApplicationException(AppResult.failure(ResultCode.FAILED_USER_NOT_EXISTS));
        }
        //4、密码校验
        String encryptPassword = MD5Util.md5(password,user.getSalt());
        if(!encryptPassword.equals(user.getPassword())){
            log.warn(ResultCode.FAILED_LOGIN.toString());
            throw new ApplicationException(AppResult.failure(ResultCode.FAILED_LOGIN.toString()));
        }
        //5、登录成功返回用户信息
        return user;
    }

    @Override
    public User selectById(Long id) {
        //非空校验
        if(id==null){
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            throw new ApplicationException(AppResult.failure(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        return userMapper.selectByPrimaryKey(id);
    }

    @Override
    public void addOneArticleCountById(Long id) {
        if(id==null || id<=0){
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            throw new ApplicationException(AppResult.failure(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        User user = userMapper.selectByPrimaryKey(id);
        if(user==null){
            log.warn(ResultCode.FAILED_USER_NOT_EXISTS.toString()+"board id:{}"+id);
            throw new ApplicationException(AppResult.failure(ResultCode.FAILED_USER_NOT_EXISTS));
        }
        //更新用户帖子数量
        User updateUser = new User();
        updateUser.setId(user.getId());
        updateUser.setArticleCount(user.getArticleCount()+1);
        int row = userMapper.updateByPrimaryKeySelective(updateUser);
        //判断影响行数
        if(row != 1){
            log.warn(ResultCode.FAILED.toString()+"受影响的行数大于1");
            throw new ApplicationException(AppResult.failure(ResultCode.FAILED));
        }
    }

    @Override
    public void subOneArticleCountById(Long id) {
        if(id==null || id<=0){
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            throw new ApplicationException(AppResult.failure(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        User user = userMapper.selectByPrimaryKey(id);
        if(user==null){
            log.warn(ResultCode.FAILED_USER_NOT_EXISTS.toString()+"board id:{}"+id);
            throw new ApplicationException(AppResult.failure(ResultCode.FAILED_USER_NOT_EXISTS));
        }
        //更新用户帖子数量
        User updateUser = new User();
        updateUser.setId(user.getId());
        updateUser.setArticleCount(user.getArticleCount()-1);
        if(updateUser.getArticleCount()<0){
            updateUser.setArticleCount(0);
        }
        int row = userMapper.updateByPrimaryKeySelective(updateUser);
        //判断影响行数
        if(row != 1){
            log.warn(ResultCode.FAILED.toString()+"受影响的行数大于1");
            throw new ApplicationException(AppResult.failure(ResultCode.FAILED));
        }
    }

    @Override
    public void modifyInfo(User user) {
        //1、非空校验
        if(user==null || user.getId()==null || user.getId()<=0){
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            throw new ApplicationException(AppResult.failure(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        //2、校验用户是否存在
        User existUser = userMapper.selectByPrimaryKey(user.getId());
        if(existUser==null){
            log.warn(ResultCode.FAILED_USER_NOT_EXISTS.toString());
            throw new ApplicationException(AppResult.failure(ResultCode.FAILED_USER_NOT_EXISTS));
        }
        //3、定义一个标志位
        boolean checkAttr = false; //false表示检验未通过

        //对每一个参数校验并且赋值
        User updateUser = new User();
        updateUser.setId(user.getId());

        //校验username
        if(!StringUtil.isEmpty(user.getUsername()) && !existUser.getUsername().equals(user.getUsername())){
            User checkUser = userMapper.selectByUserName(user.getUsername());
            //用户名也是唯一标志位
            if(checkUser!=null){
                log.warn(ResultCode.FAILED_USER_EXISTS.toString());
                throw new ApplicationException(AppResult.failure(ResultCode.FAILED_USER_EXISTS));
            }
            updateUser.setUsername(user.getUsername());
            checkAttr = true;
        }
        //校验nickname
        if(!StringUtil.isEmpty(user.getNickname()) && !existUser.getNickname().equals(user.getNickname())){
            updateUser.setNickname(user.getNickname());
            checkAttr = true;
        }
        //检验gender
        if(user.getGender()!=null && !existUser.getPassword().equals(user.getGender())){
            updateUser.setGender(user.getGender());
            //合法性校验
            if(updateUser.getGender()>2 || updateUser.getGender()<0){
                updateUser.setGender((byte)2);
            }
            checkAttr = true;
        }
        //校验email
        //如果后半句写成 existUser.getEmail().equals(user.getEmail()) 会抛出空指针异常
        if(user.getEmail()!=null && !user.getEmail().equals(existUser.getEmail())){
            updateUser.setEmail(user.getEmail());
            checkAttr = true;
        }
        //校验phone
        if(user.getPhoneNum()!=null && !user.getPhoneNum().equals(existUser.getPhoneNum())){
            updateUser.setPhoneNum(user.getPhoneNum());
            checkAttr = true;
        }
        //校验 remark
        if(user.getRemark()!=null && !user.getRemark().equals(existUser.getRemark())){
            updateUser.setRemark(user.getRemark());
            checkAttr = true;
        }

        if(!checkAttr){
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            throw new ApplicationException(AppResult.failure(ResultCode.FAILED_PARAMS_VALIDATE));
        }

        //执行更新操作
        int row = userMapper.updateByPrimaryKeySelective(updateUser);
        if(row != 1){
            log.warn(ResultCode.ERROR_SERVICES.toString());
            throw new ApplicationException(AppResult.failure(ResultCode.ERROR_SERVICES));
        }
        log.info("完成用户简介的更新");
    }

    @Override
    public void modifyPassword(Long id, String oldPassword, String newPassword) {
        //非空校验
        if(id==null || id<=0 || StringUtil.isEmpty(oldPassword) || StringUtil.isEmpty(newPassword)){
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            throw new ApplicationException(AppResult.failure(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        User user = userMapper.selectByPrimaryKey(id);
        if(user==null || user.getDeleteState()==1){
            log.warn(ResultCode.FAILED_USER_NOT_EXISTS.toString());
            throw new ApplicationException(AppResult.failure(ResultCode.FAILED_USER_NOT_EXISTS));
        }
        //校验老密码是否正确
        String oldEncryptPwd = MD5Util.md5(oldPassword, user.getSalt());
        if(!oldEncryptPwd.equals(user.getPassword())){
            log.warn(ResultCode.FAILED_OLD_PWD_ERROR.toString());
            throw new ApplicationException(AppResult.failure(ResultCode.FAILED_OLD_PWD_ERROR));
        }
        //生成新的盐值
        String salt= UUIDUtil.UUID_32();
        String newEncryptPwd = MD5Util.md5(newPassword, salt);
        Date date =new Date();
        //执行更新操作
        User updateUser = new User();
        updateUser.setId(user.getId());
        updateUser.setSalt(salt);
        updateUser.setUpdateTime(date);
        updateUser.setPassword(newEncryptPwd);
        int row = userMapper.updateByPrimaryKeySelective(updateUser);
        if(row != 1){
            log.warn(ResultCode.ERROR_SERVICES.toString());
            throw new ApplicationException(AppResult.failure(ResultCode.ERROR_SERVICES));
        }
        log.info("密码更新完成");
    }

    @Override
    public void modifyAvatar(Long id,String url){
        if(id==null || id<=0 || StringUtil.isEmpty(url)){
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            throw new ApplicationException(AppResult.failure(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        User user = userMapper.selectByPrimaryKey(id);
        if(user==null || user.getDeleteState()==1){
            log.warn(ResultCode.FAILED_USER_NOT_EXISTS.toString());
            throw new ApplicationException(AppResult.failure(ResultCode.FAILED_USER_NOT_EXISTS));
        }
        User updateUser=new User();
        updateUser.setId(user.getId());
        updateUser.setAvatarUrl(url);
        updateUser.setUpdateTime(new Date());
        int row = userMapper.updateByPrimaryKeySelective(updateUser);
        if(row != 1){
            log.warn(ResultCode.ERROR_SERVICES.toString());
            throw new ApplicationException(AppResult.failure(ResultCode.ERROR_SERVICES));
        }
        log.info("头像更新完成");
    }
}
